/*
 * guild.h
 *
 *  Created on: Jul 30, 2014
 *      Author: killerg
 */

#ifndef GUILD_H_
#define GUILD_H_


#include <unordered_map>
#include <vector>
#include <string>
#include <algorithm>
#include <assert.h>

#include "share/patterns.h"
#include "share/cs_msg.pb.h"
#include "share/json/json.h"
#include "share/rapidjson/rapidjson.h"
#include "share/rapidjson/document.h"


using namespace std;
namespace rj = rapidjson;

enum EGuildPos {
	EGP_Head = 0,
	EGP_Normal = 1,
};

struct member_t {
	int64_t playerid;
	int pos;
	int contrib;
	int lastlogon;

	void fill_info(cs::OGuildMember* info);
};

struct guild_t {
	int32_t id;
	string name;
	string intro;
	int32_t contrib;
	ptr_map<int64_t, member_t*, unordered_map<int64_t, member_t*> > members;
	set<int64_t> appliers;

	int64_t leader;
    int32_t rank;

    int64_t chged_timestamp;
    int64_t saved_timestamp;

    void add_member(int64_t playerid, EGuildPos pos);
    member_t* get_member(int64_t playerid);
    void del_member(int64_t playerid);
    void update_leader();

    void add_contrib(int64_t playerid, int32_t contrib);
	void fill_info(cs::OGuildInfo* info);

    bool initr(const rj::Value &json);
    bool saver(rj::Value &json, rj::Document::AllocatorType& al);
    bool init(const Json::Value &json);
    bool save(Json::Value &json);
};

struct guildmgr_t {
	ptr_map<int32_t, guild_t*, unordered_map<int32_t, guild_t*> > guilds;
	map<string, int32_t> name2id;
	map<int64_t, int32_t> player2guild;
	vector<guild_t*> rank;

	int guildid;

	void on_player_guildid(int64_t playerid, int32_t guildid);
	void add_rank(guild_t* guild);
	void del_rank(guild_t* guild);

	bool init();
	void destroy();
	void update(double dt);
};

#endif /* GUILD_H_ */
